//
//  ConfigCodeHelper.m
//  Honda
//
//  Created by Xiaolong Zhang on 13-4-12.
//  Copyright (c) 2013年 HeninHoo. All rights reserved.
//

#import "ConfigCodeHelper.h"
#import "NetworkManager.h"
#import "NetworkDefine.h"
#import "ZipArchiveManager.h"


@interface ConfigCodeHelper ()
@property (nonatomic, readonly) NSMutableDictionary* versionsUpdataDic;
@property (nonatomic, readonly) NSMutableDictionary* sourceUpdataDic;
@end

@implementation ConfigCodeHelper
@synthesize sourceDic           =   _sourceDic;
@synthesize serviceShopDic      =   _serviceShopDic;
@synthesize codeADic            =   _codeADic;
@synthesize codeBDic            =   _codeBDic;

@synthesize messageDic          =   _messageDic;
@synthesize emailDic            =   _emailDic;
@synthesize salersDic           =   _salersDic;
@synthesize paytypesDic         =   _paytypesDic;
@synthesize localDic            =   _localDic;
@synthesize componentDic        =   _componentDic;

@synthesize customerInfo        =   _customerInfo;
@synthesize isVersonNeedUpdate  =   _isVersonNeedUpdate;

@synthesize padDataPath         =   _padDataPath;
@synthesize versionsUpdataDic   =   _versionsUpdataDic;
@synthesize sourceUpdataDic     =   _sourceUpdataDic;

@synthesize remindDic           =   _remindDic;

static ConfigCodeHelper* s_instance = nil;
+ (ConfigCodeHelper*)shareInstance {
    if (nil == s_instance) {
        s_instance = [[ConfigCodeHelper alloc] init];
    }
    
    return s_instance;
}

- (id)init
{
    self = [super init];
    if (self) {
        _customerInfo = nil;
        _isVersonNeedUpdate = NO;
        
        BOOL isDir;
        if (!([[NSFileManager defaultManager] fileExistsAtPath:self.padDataPath isDirectory:&isDir] && isDir)) {
            NSString* resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"paddata"];
            NSError* error = nil;
            [[NSFileManager defaultManager] copyItemAtPath:resourcePath toPath:self.padDataPath error:&error];
            if (nil != error) {
                NSLog(@"Copy item error:%@", error);
            } else {
                [self initPadDataFiles];
            }
        } else {
            [self initPadDataFiles];
        }
        
        _messageDic = [[self JSONSerializationWithResourceFile:@"paddata/message.txt"] retain];
        _emailDic = [[self JSONSerializationWithResourceFile:@"paddata/email.txt"] retain];
        _salersDic = [[self JSONSerializationWithResourceFile:@"paddata/salers.txt"] retain];
        _paytypesDic = [[self JSONSerializationWithResourceFile:@"paddata/payType.txt"] retain];
        _localDic = [[self JSONSerializationWithResourceFile:@"paddata/local.txt"] retain];
        _componentDic = [[self JSONSerializationWithResourceFile:@"paddata/component.txt"] retain];
        
        _remindDic = [[self JSONSerializationWithResourceFile:@"paddata/remind.txt"] retain];
    }
    
    return self;
}

- (void)updateSourceCarsFileByKey:(NSString*)key{
    
    if ([key hasSuffix:@".zip"]) {
        if ([key isEqualToString:@"company.zip"] || [key isEqualToString:@"saleTechnique.zip"]) {

            [_sourceDic setValue:[_sourceUpdataDic objectForKey:key] forKey:key];
        } else {
            NSMutableDictionary* carsDic = [NSMutableDictionary dictionaryWithDictionary:[_sourceDic objectForKey:@"cars"]];
            NSString* value = [[_sourceUpdataDic objectForKey:@"cars"] objectForKey:key];
            [carsDic setValue:value forKey:key];
            [_sourceDic setValue:carsDic forKey:@"cars"];
        }
    } else {
        //[title isEqualToString:@"com_T8.mp4"]
        NSMutableDictionary* videoDic = [NSMutableDictionary dictionaryWithDictionary:[_sourceDic objectForKey:@"video"]];
        NSString* value = [[_sourceUpdataDic objectForKey:@"video"] objectForKey:key];
        [videoDic setValue:value forKey:key];
        [_sourceDic setValue:videoDic forKey:@"video"];
    }
    
    NSInteger ret;
    NSString* targetPath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
    writeToFile(_sourceDic, targetPath, ret);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_DownLoadComplete_Autos object:nil];
}

//证件类型
- (NSArray*)codeAIDType {
    return [self.codeADic objectForKey:@"ID_type"];
}

//非级联的代码表使用接口
- (NSArray*)codeASystematicsByPrimaryKey:(NSString*)pKey {
    return [self.codeADic objectForKey:pKey];
}

- (NSString*)codeAValueByPrimaryKey:(NSString*)pKey andSubKey:(NSString*)sKey {
    NSArray* array = [self.codeADic objectForKey:pKey];
    NSString* value = nil;
    for (NSDictionary* dic in array) {
        if ([[dic objectForKey:@"key"] isEqual:sKey]) {
            value = [dic objectForKey:@"value"];
            break;
        }
    }
    
    return value;
}

- (NSString*)codeAKeyByPrimaryKey:(NSString*)pKey andSubValue:(NSString*)sValue {
    NSArray* array = [self.codeADic objectForKey:pKey];
    NSString* key = nil;
    for (NSDictionary* dic in array) {
        if ([[dic objectForKey:@"value"] isEqual:sValue]) {
            key = [dic objectForKey:@"key"];
            break;
        }
    }
    
    return key;
}

//所在地区
- (NSArray*)codeAZoneByProvinceCode:(NSString*)pCode andCityCode:(NSString*)cCode {
    NSArray* zoneArr = [_codeADic objectForKey:@"area"];
    if (nil == pCode && nil == cCode) {
        return zoneArr;
    } else if (nil != pCode && nil == cCode) {
        for (NSDictionary* dic in zoneArr) {
            if ([[dic objectForKey:@"key"] isEqualToString:pCode]) {
                return [dic objectForKey:@"subArea"];
            }
        }
    } else if (nil != pCode && nil != cCode) {
        for (NSDictionary* dic in zoneArr) {
            if ([[dic objectForKey:@"key"] isEqualToString:pCode]) {
                NSArray* cities = [dic objectForKey:@"subArea"];
                for (NSDictionary* cityDic in cities) {
                    if ([[cityDic objectForKey:@"key"] isEqualToString:cCode]) {
                        return [cityDic objectForKey:@"subArea"];
                    }
                }
                break;
            }
        }
    }

    return nil;
}

- (NSString*)codeAZoneByProvinceCode:(NSString*)pCode andCityCode:(NSString*)cCode andAreaCode:(NSString*)aCode {
    NSString* zone = nil;
    NSArray* zoneArr = [_codeADic objectForKey:@"area"];
    for (NSDictionary* dic in zoneArr) {
        if ([[dic objectForKey:@"key"] isEqualToString:pCode]) {
            zone = [dic objectForKey:@"value"];
            if (nil != cCode) {
                NSArray* cities = [dic objectForKey:@"subArea"];
                for (NSDictionary* cityDic in cities) {
                    if ([[cityDic objectForKey:@"key"] isEqualToString:cCode]) {
                        zone = [cityDic objectForKey:@"value"];
                        if (nil != aCode) {
                            NSArray* areaArr = [cityDic objectForKey:@"subArea"];
                            for (NSDictionary* areaDic in areaArr) {
                                if ([[areaDic objectForKey:@"key"] isEqualToString:aCode]) {
                                    zone = [areaDic objectForKey:@"value"];
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }
            }
            break;
        }
    }
    
    return zone;
}

//车辆厂家、品牌
- (NSArray*)codeACarsByShopCode:(NSString*)sCode {
    if (nil == sCode) {
        return [_codeADic objectForKey:@"car_shop"];
    } else {
        NSArray* carsArr = [_codeADic objectForKey:@"car_shop"];
        for (NSDictionary* shopDic in carsArr) {
            if ([[shopDic objectForKey:@"key"] isEqualToString:sCode]) {
                return [shopDic objectForKey:@"brand"];
            }
        }
    }
    
    return nil;
}

- (NSString*)codeACarByShopCode:(NSString*)sCode andBrandCode:(NSString*)bCode {
    NSString* car = nil;
    NSArray* carsArr = [_codeADic objectForKey:@"car_shop"];
    for (NSDictionary* shopDic in carsArr) {
        if ([[shopDic objectForKey:@"key"] isEqualToString:sCode]) {
            car = [shopDic objectForKey:@"value"];
            if (nil != bCode) {
                NSArray* brandsArr = [shopDic objectForKey:@"brand"];
                for (NSDictionary* brandDic in brandsArr) {
                    if ([[brandDic objectForKey:@"key"] isEqualToString:bCode]) {
                        car = [brandDic objectForKey:@"value"];
                        break;
                    }
                }
            }
            break;
        }
    }
    
    return car;
}

//战败类型、原因
//获取所有失败类型
- (NSArray*)codeAAllDefeatedType {
    return [self.codeADic objectForKey:@"defeated_type"];
}

//获取失败类型
- (NSString*)codeADefeatedByTypeCode:(NSString*)defeatedCode {
    NSArray* defeatedTypes = [self.codeADic objectForKey:@"defeated_type"];
    NSString* defeatedTypeStr = nil;
    for (NSDictionary* type in defeatedTypes) {
        if ([[type objectForKey:@"key"] isEqual:defeatedCode]) {
            defeatedTypeStr = [type objectForKey:@"value"];
            break;
        }
    }
    
    return defeatedTypeStr;
}

//获取所有购买其他厂家车辆的原因
- (NSArray*)codeAAllBuyOtherCarCauses {
    return [[[self.codeADic objectForKey:@"defeated_type"] objectAtIndex:0] objectForKey:@"defeated_causes"];
}

//获取购买其他厂家车辆原因
- (NSString*)codeABuyOtherCarByCauseCode:(NSString*)causeCode {
    NSArray* causes = [[[self.codeADic objectForKey:@"defeated_type"] objectAtIndex:0] objectForKey:@"defeated_causes"];
    NSString* causeStr = nil;
    for (NSDictionary* type in causes) {
        if ([[type objectForKey:@"key"] isEqual:causeCode]) {
            causeStr = [type objectForKey:@"value"];
            break;
        }
    }
    
    return causeStr;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    SafeRelease(_remindDic);
    SafeRelease(_componentDic);
    SafeRelease(_localDic);
    SafeRelease(_paytypesDic);
    SafeRelease(_salersDic);
    SafeRelease(_emailDic);
    SafeRelease(_messageDic);
    SafeRelease(_codeBDic);
    SafeRelease(_codeADic);
    SafeRelease(_serviceShopDic);
    SafeRelease(_sourceDic);
    
    SafeRelease(_sourceUpdataDic);
    SafeRelease(_versionsUpdataDic);
    [super dealloc];
}

#pragma mark -
//--------------padData--------------
- (NSString*)padDataPath {
    if (![_padDataPath isKindOfClass:[NSString class]]) {
        NSArray* filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        _padDataPath = [[[filePaths objectAtIndex:0] stringByAppendingPathComponent:@"paddata"] copy];
    }
    
    return _padDataPath;
}

- (void) initPadDataFiles {
    _sourceDic = [[NSMutableDictionary alloc] initWithDictionary:[self JSONSerializationWithResourceFile:@"paddata/source.txt"]];
    _serviceShopDic = [[self JSONSerializationWithResourceFile:@"paddata/serviceshop.txt"] retain];
    _codeADic = [[self JSONSerializationWithResourceFile:@"paddata/codeA.txt"] retain];
    _codeBDic = [[self JSONSerializationWithResourceFile:@"paddata/codeB.txt"] retain];
    [self huoqubanbenhao];
    [self updataPadDataSourceByKey:@"source.txt"];
}

- (void)updataPadDataSourceByKey:(NSString*)key
{
    //http://10.251.68.91/paddata/GHAC_AfterSale/GHAC_AppVersion.txt
    NSString* urlStr = [NSString stringWithFormat:@"%@%@", PadDataURL, key];
    BOOL isDictionary = YES;
    if ([key isEqualToString:@"version"]) {
        urlStr = VersionsURL;
    } else if ([key isEqualToString:@"message"]) {
        urlStr = MessageURL;
    } else if ([key isEqualToString:@"email"]) {
        urlStr = EmailURL;
    } else if ([key isEqualToString:@"salers"]) {
        urlStr = SalersURL;
    } else if ([key isEqualToString:@"payType"]) {
        urlStr = PayTypesURL;
    } else if ([key isEqualToString:@"local"]) {
        urlStr = LocalURL;
    } else if ([key isEqualToString:@"component"]) {
        urlStr = ComponentURL;
    } else if ([key isEqualToString:@"predrive"]) {
        urlStr = PredriveURL;
        isDictionary = NO;
    }
    else if ([key isEqualToString:@"app_verson.txt"]) {

    }
    else if ([key isEqualToString:@"level"] || [key isEqualToString:@"error_code"] || [key isEqualToString:@"error_msg"]){
        return;
    }
    
    NetworkTask* task = [[NetworkTask alloc] initWithGetUrl:urlStr getArgs:nil];
    task.indentifier = key;
    if ([key isEqualToString:@"model.sqlite"]) {
        task.isDictionary = NO;
        task.isNeedProgress = YES;
        
        [task setDestFilePath:[NSString stringWithFormat:@"%@/%@", self.padDataPath, key]
                 tempFilePath:[NSString stringWithFormat:@"%@/Library/Caches/%@", NSHomeDirectory(), key]];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSuccessGetPadDataSource:) name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFailGetPadDataSource:) name:NetworkTask_NotificationName_OnFail object:task];
    
    [[NetworkManager getInstance] startTaskAsync:task level:NetworkManagerTaskLevel_Middle];
    SafeRelease(task);
}
-(void)huoqubanbenhao
{
   
    NetworkTask* task = [[NetworkTask alloc] initWithGetUrl:@"http://10.251.68.91/paddata/GHAC_AfterSale/GHAC_AppVersion.txt" getArgs:nil];
task.indentifier =@"banbenhao";
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSuccessGetPadDataSource:) name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFailGetPadDataSource:) name:NetworkTask_NotificationName_OnFail object:task];
    
    [[NetworkManager getInstance] startTaskAsync:task level:NetworkManagerTaskLevel_Middle];
    
    SafeRelease(task);

}


- (void)onSuccessGetPadDataSource:(NSNotification*)notification {
    NetworkTask* task = notification.object;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    if (0 != [[task.resultDict objectForKey:@"error_code"] intValue])
    {
        NSLog(@"%@", [task.resultDict objectForKey:@"error_msg"]);
        return;
    }
    
    NSDictionary* dici=[[NSDictionary alloc]init];
    dici= task.resultDict;
    NSLog(@"%@",dici);
    NSString* indentfier = task.indentifier;
    NSInteger ret;
    NSMutableDictionary * dic=[NSMutableDictionary dictionaryWithDictionary:dici];
    if([[dic objectForKey:@"video"] isKindOfClass:[NSDictionary class]])
    {
        NSMutableDictionary *dddd=[NSMutableDictionary dictionaryWithDictionary:[dic objectForKey:@"video"]];
        
        NSString *shipingString=[dddd objectForKey:@"com_T8.mp4"];
        [dddd removeAllObjects];
        [dddd setObject:shipingString forKey:@"com_T8.mp4"];

        [dic setObject:dddd forKey:@"video"];
  
    }


    //[[dic objectForKey:@"video"]objectForKey:@"ACC_ADS1.mp4"]
    if ([indentfier isEqualToString:@"source.txt"]) {
        _sourceUpdataDic = [[NSMutableDictionary alloc] initWithDictionary:dic];
        
        for (NSString* key in dic.allKeys) {
            
            if ([key isEqualToString:@"cars"]) {//车种压缩包
                
                NSDictionary* updateCarsDic = [dic objectForKey:key];//服务器中的车辆版本信息
                NSMutableDictionary* sourceCarsDic = [NSMutableDictionary dictionaryWithDictionary:[_sourceDic objectForKey:key]];//本地source.txt文件中的车辆版本信息
                
                NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString* autosPath = [[paths lastObject] stringByAppendingPathComponent:@"Autos"];
                
                for (NSString* sourceCarKey in sourceCarsDic.allKeys) {//删除服务器中已将删掉的车辆
                    if (![updateCarsDic.allKeys containsObject:sourceCarKey]) {
                        [sourceCarsDic removeObjectForKey:sourceCarKey];
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationReloadDownloadSourceByDeleteCarName object:sourceCarKey];
                        
                        NSString* carName = [[sourceCarKey componentsSeparatedByString:@"."] objectAtIndex:0];
                        NSString* carInfoPath = [NSString stringWithFormat:@"%@/%@", autosPath, carName];
                        if ([[NSFileManager defaultManager] fileExistsAtPath:carInfoPath]) {
                            NSError* error = nil;
                            [[NSFileManager defaultManager] removeItemAtPath:carInfoPath error:&error];//删除车辆文件
                            if (nil != error) {
                                NSLog(@"error:%@", error);
                            }
                        }
                        
                        NSString* carComponentPath = [NSString stringWithFormat:@"%@/component/%@", self.padDataPath, carName];
                        if ([[NSFileManager defaultManager] fileExistsAtPath:carComponentPath]) {
                            NSError* error = nil;
                            [[NSFileManager defaultManager] removeItemAtPath:carComponentPath error:&error];//删除车辆的精品文件
                            if (nil != error) {
                                NSLog(@"error:%@", error);
                            }
                        }
                    }
                }
                
                [_sourceDic setValue:sourceCarsDic forKey:key];
                
                NSInteger ret;
                NSString* targetPath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
                //////////////////////
                //writeToFile(_sourceDic, targetPath, ret);
                
//                for (NSString* updateCarKey in updateCarsDic.allKeys) {
//                    
//                    if (![[[_sourceDic objectForKey:@"cars"] allKeys] containsObject:updateCarKey]) {//服务器中有新添加的车辆，更新本地source.txt文件，车辆默认版本信息为“NA”
//                        [sourceCarsDic setValue:@"NA" forKey:updateCarKey];
//                        [_sourceDic setValue:sourceCarsDic forKey:@"cars"];
//                        
//                        NSInteger ret;
//                        NSString* targetPath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
//                        writeToFile(_sourceDic, targetPath, ret);
//                        
//                        //[[NSNotificationCenter defaultCenter] postNotificationName:NotificationReloadDownloadSourceByAddCarName object:updateCarKey];
//                    }
//                    
//                    if (![[updateCarsDic objectForKey:updateCarKey] isEqualToString:[[_sourceDic objectForKey:@"cars"] objectForKey:updateCarKey]]) {//如果本地车辆版本信息与服务端不相等，发车辆更新消息
//                        //[[NSNotificationCenter defaultCenter] postNotificationName:NotificationCarInfoShouldUpdate object:updateCarKey];
//                    }
//                }
               //////////////////////////
            }
            else if ([key hasSuffix:@".zip"]) {//走进广本和本田科技压缩包 销售技能压缩包
                if (![[_sourceUpdataDic objectForKey:key] isEqualToString:[_sourceDic objectForKey:key]]) {
                    [_sourceDic setValue:@"NA" forKey:key];
                    NSString* targetPath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
                    writeToFile(_sourceDic, targetPath, ret);
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationCarInfoShouldUpdate object:key];
                }
                
            }
            
/***************************************end of 视频下载******************************************/
            else if ([key isEqualToString:@"video"]){//视频
                NSDictionary* serviceVideoDic = [_sourceUpdataDic objectForKey:key];
                NSMutableDictionary* localVideoDic = [NSMutableDictionary dictionaryWithDictionary:[_sourceDic objectForKey:key]];
                
                NSLog(@"serviceVideoDic ＝ %@",serviceVideoDic);
                NSLog(@"localVideoDic ＝ %@",localVideoDic);
                
                if (![serviceVideoDic isEqualToDictionary:localVideoDic]) {
                    for (NSString* localVideoKey in localVideoDic.allKeys) {//删除视频文件名字段
                        if (![serviceVideoDic.allKeys containsObject:localVideoKey]) {//本地的视频文件名字段是否存在服务器中
                            [localVideoDic removeObjectForKey:localVideoKey];
                            [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/video/%@", self.padDataPath, localVideoKey] error:nil];
                            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationReloadDownloadSourceByDeleteCarName object:localVideoKey];
                        }
                    }
                    
                    [_sourceDic setValue:localVideoDic forKey:key];
                    
                    NSInteger ret;
                    NSString* targetPath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
                    writeToFile(_sourceDic, targetPath, ret);
                    
                    for (NSString* serviceVideoKey in serviceVideoDic.allKeys) {//增加视频文件名字段
                        if (![localVideoDic.allKeys containsObject:serviceVideoKey]) {//服务器的视频文件名字段是否存在本地中
                            [localVideoDic setObject:@"NA" forKey:serviceVideoKey];
                            
                            [_sourceDic setValue:localVideoDic forKey:key];
                            
                            NSInteger ret;
                            NSString* targetPath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
                            writeToFile(_sourceDic, targetPath, ret);
                            
                            NSLog(@"serviceVideoKey = %@",serviceVideoKey);
                            
//                            if ([serviceVideoKey isEqualToString:@"com_T8.mp4"])
//                            {
                                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationReloadDownloadSourceByAddCarName object:serviceVideoKey];
//                            }
                        }
                        
                        if (![[serviceVideoDic objectForKey:serviceVideoKey] isEqualToString:[[_sourceDic objectForKey:key] objectForKey:serviceVideoKey]])
                        {
                            NSLog(@"[serviceVideoDic objectForKey:serviceVideoKey] = %@",[serviceVideoDic objectForKey:serviceVideoKey]);
//                            if ([serviceVideoKey isEqualToString:@"com_T8.mp4"])
//                            {
                                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationCarInfoShouldUpdate object:serviceVideoKey];
                                
//                            }
                        }
                    }
                }
                
            } else {
                if (![[dic objectForKey:key] isEqualToString:[_sourceDic objectForKey:key]]) {
                    [self updataPadDataSourceByKey:key];
                }
            }
/***************************************end of 视频下载******************************************/
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationDidCheckSourceFile object:nil];//发送“检查完成source.txt文件”消息
        
    }
    else if ([indentfier isEqualToString:@"version"]){
        _versionsUpdataDic = [[NSMutableDictionary alloc] initWithDictionary:dic];
        for (NSString* key in dic.allKeys)
        {
            if (![[dic objectForKey:key] isEqual:[_sourceDic objectForKey:key]])
            {
                [self updataPadDataSourceByKey:key];
            }
            else if ([key isEqualToString:@"local"])
            {
                NSDictionary* dic = @{@"name": key, @"dic": [self JSONSerializationWithResourceFile:@"paddata/local.txt"], @"isNeedUpdate": [NSNumber numberWithBool:NO]};
                [self performSelectorInBackground:@selector(setLocalDicOrComponentDic:) withObject:dic];
            }
            else if ([key isEqualToString:@"component"])
            {
//                NSLog(@"%@",[self JSONSerializationWithResourceFile:@"paddata/component.txt"]);
//                NSDictionary* dic = @{@"name": key, @"dic": [self JSONSerializationWithResourceFile:@"paddata/component.txt"], @"isNeedUpdate": [NSNumber numberWithBool:NO]};
//                
//                NSLog(@"%@",dic);
//                
//                [self performSelectorInBackground:@selector(setLocalDicOrComponentDic:) withObject:dic];
            }
        }
        
    }
    else if ([indentfier isEqualToString:@"model.sqlite"]){
        [_sourceDic setValue:[_sourceUpdataDic objectForKey:indentfier] forKey:indentfier];
        NSString* targetPath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
        writeToFile(_sourceDic, targetPath, ret);
        
    }
    else if ([indentfier isEqualToString:@"predrive"]){
        if ([task.resultData writeToFile:[NSString stringWithFormat:@"%@/RoadLine.jpg", self.padDataPath] atomically:YES]) {
            [_sourceDic setValue:[_versionsUpdataDic objectForKey:indentfier] forKey:indentfier];
            NSString* path = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
            writeToFile(_sourceDic, path, ret);
        }
        
    }
    else if ([indentfier isEqualToString:@"component"]) {
        NSDictionary* argcDic = @{@"name": @"component", @"dic": dic, @"isNeedUpdate": [NSNumber numberWithBool:YES]};
        [self performSelectorInBackground:@selector(setLocalDicOrComponentDic:) withObject:argcDic];
        
    }
    else if ([indentfier isEqualToString:@"banbenhao"])
    {
        NSString* updataVerson = [task.resultDict objectForKey:@"GHAC_AppVersion"];
        NSString* currentVerson = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        
        if (updataVerson.floatValue > currentVerson.floatValue) {
            [[NetworkingViewController sharedController] dismissNetworking];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPUpdateURL]];
        }

    }
    else {
        NSString* targetPath = nil;
        if ([indentfier hasSuffix:@".txt"]) {
            targetPath = [NSString stringWithFormat:@"%@/%@", self.padDataPath, indentfier];
        } else {
            targetPath = [NSString stringWithFormat:@"%@/%@.txt", self.padDataPath, indentfier];
        }
        writeToFile(dic, targetPath, ret);
        if (0 != ret) {
            [self updataPadDataByFileName:indentfier];
            if ([indentfier isEqualToString:@"serviceshop.txt"] || [indentfier isEqualToString:@"codeA.txt"] || [indentfier isEqualToString:@"codeB.txt"]) {
                [_sourceDic setValue:[_sourceUpdataDic objectForKey:indentfier] forKey:indentfier];
            } else {
                [_sourceDic setValue:[_versionsUpdataDic objectForKey:indentfier] forKey:indentfier];
            }
            targetPath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
            writeToFile(_sourceDic, targetPath, ret);
        }
    }
    
}

- (void)onFailGetPadDataSource:(NSNotification*)notification {
    NetworkTask* task = notification.object;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    NSLog(@"%@ onFailGetPadDataSource", task.indentifier);
}

- (void)updataPadDataByFileName:(NSString*)name {
    if ([name isEqualToString:@"serviceshop.txt"]) {
        SafeRelease(_serviceShopDic);
        _serviceShopDic = [[self JSONSerializationWithResourceFile:@"paddata/serviceshop.txt"] retain];
    } else if ([name isEqualToString:@"codeA.txt"]) {
        SafeRelease(_codeADic);
        _codeADic = [[self JSONSerializationWithResourceFile:@"paddata/codeA.txt"] retain];
    } else if ([name isEqualToString:@"codeB.txt"]) {
        SafeRelease(_codeBDic);
        _codeBDic = [[self JSONSerializationWithResourceFile:@"paddata/codeB.txt"] retain];
    } else if ([name isEqualToString:@"message"]) {
        SafeRelease(_messageDic);
        _messageDic = [[self JSONSerializationWithResourceFile:@"paddata/message.txt"] retain];
    } else if ([name isEqualToString:@"email"]) {
        SafeRelease(_emailDic);
        _emailDic = [[self JSONSerializationWithResourceFile:@"paddata/email.txt"] retain];
    } else if ([name isEqualToString:@"salers"]) {
        SafeRelease(_salersDic);
        _salersDic = [[self JSONSerializationWithResourceFile:@"paddata/salers.txt"] retain];
    } else if ([name isEqualToString:@"local"]) {
        NSDictionary* dic = @{@"name": name, @"dic": [self JSONSerializationWithResourceFile:@"paddata/local.txt"], @"isNeedUpdate": [NSNumber numberWithBool:YES]};
        [self performSelectorInBackground:@selector(setLocalDicOrComponentDic:) withObject:dic];
//    } else if ([name isEqualToString:@"component"]) {
//        NSDictionary* dic = @{@"name": name, @"dic": [self JSONSerializationWithResourceFile:@"paddata/component.txt"], @"isNeedUpdate": [NSNumber numberWithBool:YES]};
//        [self performSelectorInBackground:@selector(setLocalDicOrComponentDic:) withObject:dic];
    } else if ([name isEqualToString:@"payType"]) {
        SafeRelease(_paytypesDic);
        _paytypesDic = [[self JSONSerializationWithResourceFile:@"paddata/payType.txt"] retain];
    }
}

- (NSDictionary*)JSONSerializationWithResourceFile:(NSString*)fileName {
//    NSLog(@"fileName: %@", fileName);
    NSString* path = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), fileName];
    NSData* data = [NSData dataWithContentsOfFile:path];
    
    return [self JSONSerializationWithData:data];
}

- (NSDictionary*)JSONSerializationWithData:(NSData*)data {
    if (![data isKindOfClass:[NSData class]]) {
        return nil;
    }
    
    NSError* error = nil;
    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (nil != error) {
        NSLog(@"JSON error :%@", error);
    }
    
    return dic;
}

- (BOOL)isDirectoryExist:(NSString*)directoryPath {
    BOOL isDirectory = NO;
	BOOL result = [[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDirectory];
	return result&isDirectory;
}

- (void)setLocalDicOrComponentDic:(NSDictionary*)parameterDic {
    NSDictionary* dic = [NSDictionary dictionaryWithDictionary:[parameterDic objectForKey:@"dic"]];
    
    
    NSLog(@"/****************************************/%@",dic);
    
    NSString* fileName = [parameterDic objectForKey:@"name"];
    BOOL isNeedUpdate = [(NSNumber*)[parameterDic objectForKey:@"isNeedUpdate"] boolValue];
    
    if ([fileName isEqualToString:@"local"]) {
        [self setLocalDic:dic isNeedUpdate:isNeedUpdate];
    } else if ([fileName isEqualToString:@"component"]) {
        [self setComponentDic:dic isNeedUpdate:isNeedUpdate];
    }
}

//解析local.txt文件，并且下载指定的文件
- (void)setLocalDic:(NSDictionary *)localDic isNeedUpdate:(BOOL)isNeedUpdate {
    if (isNeedUpdate) {
        SafeRelease(_localDic);
        _localDic = [localDic retain];
    }
        
    for (NSString* key in self.localDic.allKeys) {
        NSArray* picArr = nil;
        if ([key isEqualToString:@"summary"]
            || [key isEqualToString:@"honor"]
            || [key isEqualToString:@"history"]
            || [key isEqualToString:@"right"]
            || [key isEqualToString:@"strength"]) {
            
            picArr = [[_localDic objectForKey:key] objectForKey:@"pic"];
            
        } else if ([key isEqualToString:@"activities"]) {
            picArr = [_localDic objectForKey:key];
        } else {
            continue;
        }
        
        NSString* isActivitiesKey = [key isEqualToString:@"activities"]?@"activities/":@"";
        NSString* path = [NSString stringWithFormat:@"%@/local/%@", self.padDataPath, isActivitiesKey];
        if (isNeedUpdate) {
            [self removeFilesInPath:path byInfoArray:picArr indentifier:@"local"];
        }
        
        for (NSString* picName in picArr) {
            NSString* urlStr = [NSString stringWithFormat:@"%@%@", CurShopInfoURL, picName];
            NSString* indentifier = [NSString stringWithFormat:@"%@%@", path, picName];
            NSString* tempPath = [NSString stringWithFormat:@"%@/Library/Caches/local_%@_%@.jpg", NSHomeDirectory(), key, picName];
            
            [self downloadPicWithUrlPath:urlStr indentifier:indentifier tempPath:tempPath isNeedUpdate:isNeedUpdate];
        }
        
    }
}

//设置精品Dictionary，并且解析成指定文件放到对应的车种文件夹中
- (void)setComponentDic:(NSDictionary *)componentDic isNeedUpdate:(BOOL)isNeedUpdate{
    if (isNeedUpdate) {
        SafeRelease(_componentDic);
        _componentDic = [componentDic retain];
    }
    
    NSArray* componentArr = [_componentDic objectForKey:@"result"];
    
    NSInteger ret = 0;
    NSString* componentFilePath = [NSString stringWithFormat:@"%@/component.txt", self.padDataPath];
    
    if (0 == componentArr.count) {//如果“result”为空，删除所有component文件夹下的文件
        NSError* err = nil;
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/component/", self.padDataPath] error:&err];
        if (nil != err) {
            NSLog(@"delete 'component' files error:%@", err);
        }
        
        writeToFile(_componentDic, componentFilePath, ret);//write into 'component.txt' file
        
    } else {
        NSMutableDictionary* fileDic = nil;
        NSMutableArray* fileResultArr = nil;
        if (![[NSFileManager defaultManager] fileExistsAtPath:componentFilePath]) {
            fileDic = [[[NSMutableDictionary alloc] init] autorelease];
            fileResultArr = [[[NSMutableArray alloc] init] autorelease];
            [fileDic setValue:fileResultArr forKey:@"result"];
            
            writeToFile(fileDic, componentFilePath, ret);//write into 'component.txt' file
        } else {
            fileDic = [[NSMutableDictionary alloc] initWithDictionary:[self JSONSerializationWithResourceFile:@"paddata/component.txt"]];
            fileResultArr = [[[NSMutableArray alloc] initWithArray:[fileDic objectForKey:@"result"]] autorelease];
        }
        
        NSMutableArray* component0Arr = [[[NSMutableArray alloc] init] autorelease];//广本精品array
        NSMutableArray* component1Arr = [[[NSMutableArray alloc] init] autorelease];//特约店精品array
        
        for (NSDictionary* dic in componentArr) {//获取所有精品的id，为了删除过期的精品文件
            NSString* source = [NSString stringWithFormat:@"%@", [dic objectForKey:@"source"]];
            if ([source isEqualToString:@"0"]) {
                [component0Arr addObject:[NSString stringWithFormat:@"%@", [dic objectForKey:@"id"]]];
            } else if ([source isEqualToString:@"1"]){
                [component1Arr addObject:[NSString stringWithFormat:@"%@", [dic objectForKey:@"id"]]];
            }
        }
        
        for (NSString* carClass in self.codeBDic.allKeys) {//删除过期的精品文件
            [self removeFilesInPath:[NSString stringWithFormat:@"%@/component/%@/0/", self.padDataPath, carClass]
                        byInfoArray:component0Arr
                        indentifier:@"component"];
            [self removeFilesInPath:[NSString stringWithFormat:@"%@/component/%@/1/", self.padDataPath, carClass]
                        byInfoArray:component1Arr
                        indentifier:@"component"];
        }
        
        for (NSDictionary* dic1 in componentArr) {
            NSString* content = [NSString stringWithFormat:@"%@\n参考价:%@", [dic1 objectForKey:@"des"], [dic1 objectForKey:@"price"]];
            NSString* bigimage = [NSString stringWithFormat:@"%@_LargeImage.jpg", [dic1 objectForKey:@"id"]];
            NSString* middleimage = [NSString stringWithFormat:@"%@_MiddleImage.jpg", [dic1 objectForKey:@"id"]];
            NSString* source = [NSString stringWithFormat:@"%@", [dic1 objectForKey:@"source"]];
            NSString* indentifier = [NSString stringWithFormat:@"%@", [dic1 objectForKey:@"id"]];
            NSString* version = [dic1 objectForKey:@"version"];
            NSArray* carType = [dic1 objectForKey:@"cartypes"];
            BOOL isVersionUpDate = YES;
            
            for (NSDictionary* dic2 in fileResultArr) {
                if ([indentifier isEqualToString:[NSString stringWithFormat:@"%@", [dic2 objectForKey:@"id"]]]) {
                    if (![version isEqualToString:[dic2 objectForKey:@"version"]]) {
                        
                        NSArray* dic2CarType = [dic2 objectForKey:@"cartypes"];
                        NSMutableArray* carClassNames = [[[NSMutableArray alloc] init] autorelease];;
                        
                        for (NSString* typeStr in dic2CarType) {
                            NSString* carClassStr = [self codeBCarClassByCarTypeKey:typeStr];
                            if ([NSString validString:carClassStr] && ![carClassNames containsObject:carClassStr]) {
                                NSString* path = [NSString stringWithFormat:@"%@/component/%@/%@/", self.padDataPath, carClassStr, [NSString stringWithFormat:@"%@", [dic2 objectForKey:@"source"]]];
                                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@.tpl", path, indentifier] error:nil];
                                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@_LargeImage.jpg", path, indentifier] error:nil];
                                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@_MiddleImage.jpg", path, indentifier] error:nil];
                                [carClassNames addObject:carClassStr];
                            }
                        }
                    } else {
                        isVersionUpDate = NO;
                    }
                    break;
                }
            }

            NSMutableDictionary* tplDic = [[[NSMutableDictionary alloc] init] autorelease];
            [tplDic setValue:@"MixTemplateView" forKey:@"template"];
            [tplDic setValue:middleimage forKey:@"middleimage"];
            [tplDic setValue:bigimage forKey:@"bigimage"];
            [tplDic setValue:[dic1 objectForKey:@"name"] forKey:@"text"];
            [tplDic setValue:content forKey:@"content"];
            [tplDic setValue:version forKey:@"version"];

            
            if (0 == carType.count) {

                for (NSString* carClass in self.codeBDic.allKeys) {
                    NSString* path = [NSString stringWithFormat:@"%@/component/%@/%@/", self.padDataPath, carClass, source];
                    BOOL isDir;
                    if (!([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir] && isDir)) {
                        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
                    }

                    NSString* filePath = [NSString stringWithFormat:@"%@%@.tpl", path, indentifier];

                    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath] || isNeedUpdate) {
                        NSInteger ret;
                        writeToFile(tplDic, filePath, ret);
                    }

                    [self downloadPicWithUrlPath:[NSString stringWithFormat:@"%@%@", ComponentPicURL, [dic1 objectForKey:@"pic"]]
                                                 indentifier:[NSString stringWithFormat:@"%@%@_", path, indentifier]
                                                 tempPath:[NSString stringWithFormat:@"%@/Library/Caches/component_%@_%@_%@.jpg", NSHomeDirectory(), carClass, source, indentifier]
                                             isNeedUpdate:isVersionUpDate];
                }

            } else {
                
                NSMutableArray* carClassArr = [[[NSMutableArray alloc] init] autorelease];
                
                for (NSString* typeStr in carType) {
                    NSString* carClass = [self codeBCarClassByCarTypeKey:typeStr];
                    if ([NSString invalidString:carClass]) {
                        continue;
                    }
                    
                    if (![carClassArr containsObject:carClass]) {
                        [carClassArr addObject:carClass];
                    } else {
                        continue;
                    }

                    NSString* path = [NSString stringWithFormat:@"%@/component/%@/%@/", self.padDataPath, carClass, source];
                    BOOL isDir;
                    if (!([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir] && isDir)) {
                        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
                    }

                    NSString* filePath = [NSString stringWithFormat:@"%@%@.tpl", path, indentifier];

                    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath] || isNeedUpdate) {
                        NSInteger ret;
                        writeToFile(tplDic, filePath, ret);
                    }
                    
                    [self downloadPicWithUrlPath:[NSString stringWithFormat:@"%@%@", ComponentPicURL, [dic1 objectForKey:@"pic"]]
                                                 indentifier:[NSString stringWithFormat:@"%@%@_", path, indentifier]
                                                 tempPath:[NSString stringWithFormat:@"%@/Library/Caches/component_%@_%@_%@_%@.jpg", NSHomeDirectory(), carClass, typeStr, source, indentifier]
                                             isNeedUpdate:isVersionUpDate];
                }
            }
            
            [fileResultArr addObject:dic1];
            if (isNeedUpdate) {
                [fileDic setValue:fileResultArr forKey:@"result"];
                writeToFile(_componentDic, componentFilePath, ret);//write into 'component.txt' file
            }
        }
    }
    
    if (isNeedUpdate) {
        [_sourceDic setValue:[_versionsUpdataDic objectForKey:@"component"] forKey:@"component"];
        NSString* sourceFilePath = [NSString stringWithFormat:@"%@/source.txt", self.padDataPath];
        writeToFile(_sourceDic, sourceFilePath, ret);
    }
    
}

//删掉过期的缓存图片
- (void)removeFilesInPath:(NSString*)path byInfoArray:(NSArray*)array indentifier:(NSString*) indentifier{
    NSArray* filesArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    if ([indentifier isEqualToString:@"component"]) {
        for (NSString* fileName in filesArr) {
            if ([fileName hasSuffix:@".tpl"]) {
                NSString* obj = [[fileName componentsSeparatedByString:@"."] firstObject];
                if (![array containsObject:obj]) {
                    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@.tpl", path, obj] error:nil];
                    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@_LargeImage.jpg", path, obj] error:nil];
                    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@_MiddleImage.jpg", path, obj] error:nil];
                }
            }
        }
    } else if ([indentifier isEqualToString:@"local"]) {
        for (NSString* fileName in filesArr) {
            if (![array containsObject:fileName] && ![fileName isEqualToString:@"activities"]) {
                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", path, fileName] error:nil];
            }
        }
    }
}

//codeB中根据车型获取车种
- (NSString*)codeBCarClassByCarTypeKey:(NSString*)carclassKey {
    for (NSString* classKey in self.codeBDic.allKeys) {
        NSArray* typeArr = [self.codeBDic objectForKey:classKey];
        for (NSDictionary* typeDic in typeArr) {
            if ([carclassKey isEqualToString:[typeDic objectForKey:@"key"]]) {
                return classKey;
            }
        }
    }
    
    return nil;
}

//下载component、local图片
- (void)downloadPicWithUrlPath:(NSString*)urlPath indentifier:(NSString*)indentifier tempPath:(NSString*)tempPath isNeedUpdate:(BOOL)isNeedUpdate{
    
    NSString* destPath = indentifier;
    
    if (NSNotFound != [indentifier rangeOfString:@"component"].location) {
        destPath = [NSString stringWithFormat:@"%@LargeImage.jpg", indentifier];
    } 
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:destPath] && !isNeedUpdate) {
        if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@MiddleImage.jpg", indentifier]]) {
//            [self performSelectorInBackground:@selector(compressComponentPicturesByPath:) withObject:indentifier];
            [self compressComponentPicturesByPath:indentifier];
        }
        
        return;
    }
    
    NetworkTask* task = [[NetworkTask alloc] initWithGetUrl:urlPath getArgs:nil];
    task.indentifier = indentifier;
    task.isDictionary = NO;
    task.isNeedProgress = YES;
    
    [task setDestFilePath:destPath tempFilePath:tempPath];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSuccessDownloadPic:) name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFailDownloadPic:) name:NetworkTask_NotificationName_OnFail object:task];
    
    [[NetworkManager getInstance] startTaskAsync:task level:NetworkManagerTaskLevel_Middle];
    
    SafeRelease(task);
}

- (void)onSuccessDownloadPic:(NSNotification*)notification {
    NetworkTask* task = notification.object;
    NSString* indentifier = [task.indentifier copy];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    if (0 != [[task.resultDict objectForKey:@"error_code"] intValue]) {
        NSLog(@"%@", [task.resultDict objectForKey:@"error_msg"]);
        return;
    }
    
    if (NSNotFound != [indentifier rangeOfString:@"component"].location) {
        [self performSelectorInBackground:@selector(compressComponentPicturesByPath:) withObject:indentifier];
    }
}

- (void)onFailDownloadPic:(NSNotification*)notification {
    NetworkTask* task = notification.object;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
}

- (void)compressComponentPicturesByPath:(NSString*)path {
    UIImage* image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@LargeImage.jpg", path]];
    CGSize middleSize = CGSizeMake(1312, 985);
    UIGraphicsBeginImageContext(middleSize);
    [image drawInRect:CGRectMake(0, 0, middleSize.width, middleSize.height)];
    UIImage* middleImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSData* data = UIImageJPEGRepresentation(middleImage, 0);
    [data writeToFile:[NSString stringWithFormat:@"%@MiddleImage.jpg", path] atomically:NO];
}

- (NSDictionary *)dictionaryInArrayedDictionaries:(NSArray *)array forKeyvalue:(NSString *)keyvalue {
    __block NSDictionary * result = nil;
    if ([NSArray validArray:array] && [NSString validString:keyvalue]) {
        [array enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSDictionary * dictionary, NSUInteger index, BOOL *stop) {
            if ([NSDictionary validDictionary:dictionary]
                && [NSString validString:[dictionary objectForNilOrKey:kCodeKey]]
                && [keyvalue isEqualToString:[dictionary objectForNilOrKey:kCodeKey]]) {
                result = dictionary;
                *stop = YES;
            }
        }];
    }
    
    return result;
}

- (NSDictionary *)carinfosFromCarclassKey:(NSString *)carclassKey cartypeKey:(NSString *)cartypeKey outsideColorKey:(NSString *)outsideColorKey insideColorKey:(NSString *)insideColorKey {
    if ([NSString invalidString:carclassKey] || [NSString invalidString:cartypeKey]) {
        return nil;
    }
    
    NSArray * carclass = [[ConfigCodeHelper shareInstance].codeBDic objectForKey:carclassKey];
    if ([NSArray invalidArray:carclass]) {
        return nil;
    }
    
    NSDictionary * cartype = [self dictionaryInArrayedDictionaries:carclass forKeyvalue:cartypeKey];
    if ([NSDictionary invalidDictionary:cartype]) {
        return nil;
    }
    
    NSMutableDictionary * carinfos = [NSMutableDictionary dictionaryWithObject:[cartype objectForNilOrKey:kCodeValue]
                                                                        forKey:@"cartype"];
    
    NSDictionary * outside = [self dictionaryInArrayedDictionaries:[cartype objectForNilOrKey:@"o_color"]
                                                       forKeyvalue:outsideColorKey];
    if ([NSDictionary validDictionary:outside]) {
        [carinfos setObject:[outside objectForNilOrKey:kCodeValue] forKey:@"outside"];
    }
    
    NSDictionary * inside = [self dictionaryInArrayedDictionaries:[cartype objectForNilOrKey:@"i_color"]
                                                      forKeyvalue:insideColorKey];
    if ([NSDictionary validDictionary:inside]) {
        [carinfos setObject:[inside objectForNilOrKey:kCodeValue] forKey:@"inside"];
    }
    
    return carinfos;
}

- (NSString *)stringFromMessageSource:(NSString *)messageSource otherSource:(NSString *)otherSource {
    NSMutableString * string = [NSMutableString string];
    NSArray * keysArray = [self keysArrayFromMessageSource:messageSource];
    for (NSString * key in keysArray) {
        if ([NSString invalidString:key] || [key isEqualToString:@"5"]) {
            continue;
        }
        NSString * message = [self codeAValueByPrimaryKey:@"sources" andSubKey:key];
        if ([NSString invalidString:message]) {
            continue;
        }
        if ([NSString validString:string]) {
            [string appendString:@", "];
        }
        
        [string appendString:message];
    }
    if ([self containOhterSourceInKeysArray:keysArray] && [NSString validString:otherSource]) {
        if ([NSString validString:string]) {
            [string appendString:@", "];
        }
        [string appendFormat:@"其他-%@", otherSource];
    }
    
    return string;
}

- (NSArray *)keysArrayFromMessageSource:(NSString *)messageSource  {
    NSMutableArray * keysArray = [NSMutableArray array];
    for (NSUInteger index = 0; index < messageSource.length; ++index) {
        if ([NSNumber numberWithInt:[[messageSource substringWithRange:NSMakeRange(index, 1)] intValue]].boolValue) {
            [keysArray addObject:[@(index + 1) description]];
        }
    }
    
    return keysArray;
}

- (BOOL)containOhterSourceInKeysArray:(NSArray *)keysArray {
    for (NSString * key in keysArray) {
        if ([@"5" isEqualToString:key]) {
            return YES;
        }
    }
    
    return NO;
}

- (BOOL)containOhterSourceInMessageSource:(NSString *)messageSource {
    return [self containOhterSourceInKeysArray:[self keysArrayFromMessageSource:messageSource]];
}

- (NSString *)messageSourceFromkeysArray:(NSArray *)keysArray {
    NSMutableString * messageSource = [NSMutableString string];
    NSArray * sources = [self codeASystematicsByPrimaryKey:@"sources"];
    for (NSUInteger index = 0; index < sources.count; ++index) {
        [messageSource appendString:@"0"];
    }
    for (NSString * key in keysArray) {
        if ([NSString invalidString:key]) {
            continue;
        }
        NSUInteger index = [key intValue] - 1;
        if (index < messageSource.length) {
            [messageSource replaceCharactersInRange:NSMakeRange(index, 1) withString:@"1"];
        }
    }
    
    return messageSource;
}

- (NSString *)stringFromHobbies:(NSString *)hobbies {
    NSArray * hobbykeys = [self hobbykeysFromHobbies:hobbies];
    if ([NSArray invalidArray:hobbykeys]) {
        return nil;
    }
    
    NSMutableString * string = [NSMutableString string];
    for (NSString * key in hobbykeys) {
        NSString * hobby = [self codeAValueByPrimaryKey:@"hobby" andSubKey:key];
        if ([NSString invalidString:hobby]) {
            continue;
        }
        
        if ([NSString validString:string]) {
            [string appendString:@", "];
        }
        [string appendString:hobby];
    }
    
    return string;
}

- (NSArray *)hobbykeysFromHobbies:(NSString *)hobbies {
    if ([NSString invalidString:hobbies]) {
        return nil;
    }

    return [hobbies componentsSeparatedByString:@","];
}

- (NSString *)hobbiesFromHobbykeys:(NSArray *)hobbykeys {
    if ([NSArray invalidArray:hobbykeys]) {
        return @"";
    }
    
    NSMutableString * string = [NSMutableString string];
    for (NSString * key in hobbykeys) {
        if ([NSString invalidString:key]) {
            continue;
        }
        
        if ([NSString validString:string]) {
            [string appendString:@","];
        }
        [string appendString:key];
    }

    return string;
}

- (NSString *)locationStringByProvinceCode:(NSString *)pCode andCityCode:(NSString *)cCode andAreaCode:(NSString *)aCode {
    if ([NSString invalid:pCode]) {
        return nil;
    }
    
    NSDictionary * province = [self dictionaryInArrayedDictionaries:[_codeADic objectForNilOrKey:kCodeArea] forKeyvalue:pCode];
    if ([NSDictionary invalidDictionary:province] || [NSString invalidString:[province objectForNilOrKey:kCodeValue]]) {
        return nil;
    }
    
    NSDictionary * city = [self dictionaryInArrayedDictionaries:[province objectForNilOrKey:kCodeSubarea] forKeyvalue:cCode];
    if ([NSDictionary invalidDictionary:city] || [NSString invalidString:[city objectForNilOrKey:kCodeValue]]) {
        return [province objectForNilOrKey:kCodeValue];
    }
    
    NSString * locationString = [province objectForNilOrKey:kCodeValue];
    if (! [[province objectForNilOrKey:kCodeValue] isEqualToString:[city objectForNilOrKey:kCodeValue]]
           && ! [[city objectForNilOrKey:kCodeValue] isEqualToString:@"市辖区"]
           && ! [[city objectForNilOrKey:kCodeValue] isEqualToString:@"县"]) {
        locationString = [locationString stringByAppendingFormat:@", %@", [city objectForNilOrKey:kCodeValue]];
    }
    
    NSDictionary * area = [self dictionaryInArrayedDictionaries:[city objectForNilOrKey:kCodeSubarea] forKeyvalue:aCode];
    if ([NSDictionary invalidDictionary:area] || [NSString invalidString:[area objectForNilOrKey:kCodeValue]]) {
        return locationString;
    }
    
    return [locationString stringByAppendingFormat:@", %@", [area objectForNilOrKey:kCodeValue]];
}

//短信模板代码表转换
-(NSMutableArray*)getModelCode
{
    NSArray* arr = [_messageDic objectForKey:@"results"];
    NSMutableArray* array = [[NSMutableArray new] autorelease];
    for (int i=0; i<[arr count]; i++) {
        NSDictionary* curDic = [arr objectAtIndex:i];
        NSMutableDictionary* dic = [NSMutableDictionary new];
        [dic setObject:[curDic objectForKey:@"id"] forKey:@"key"];
        [dic setObject:[curDic objectForKey:@"name"] forKey:@"value"];
        [array addObject:dic];
        SafeRelease(dic);
    }
    return array;
}

//按照id查找对应的模板对象
-(NSString*)getModelContentByKey:(NSString*)str
{
    NSString* content = nil;
    NSArray* arr = [_messageDic objectForKey:@"results"];
    for (int i=0; i<[arr count]; i++) {
        NSDictionary* curDic = [arr objectAtIndex:i];
        if ([str isEqualToString:[curDic objectForKey:@"id"]]) {
            content = [curDic objectForKey:@"content"];
            break;
        }
    }
    return content;
}

//邮件模板代码表转换
-(NSMutableArray*)getEmailModelCode
{
    NSArray* arr = [_emailDic objectForKey:@"results"];
    NSMutableArray* array = [[NSMutableArray new] autorelease];
    for (int i=0; i<[arr count]; i++) {
        NSDictionary* curDic = [arr objectAtIndex:i];
        NSMutableDictionary* dic = [NSMutableDictionary new];
        [dic setObject:[curDic objectForKey:@"id"] forKey:@"key"];
        [dic setObject:[curDic objectForKey:@"name"] forKey:@"value"];
        [array addObject:dic];
        SafeRelease(dic);
    }
    return array;
}

//按照id查找对应的邮件模板对象
- (NSDictionary*)getEmailModelDictionaryByKey:(NSString*)str {
    NSDictionary* dic = nil;
    NSArray* arr = [_emailDic objectForKey:@"results"];
    for (int i=0; i<[arr count]; i++) {
        NSDictionary* curDic = [arr objectAtIndex:i];
        if ([str isEqualToString:[curDic objectForKey:@"id"]]) {
            dic = curDic;
            break;
        }
    }
    
    return dic;
}

////按照id查找对应的邮件模板对象
//-(NSString*)getEmailModelContentByKey:(NSString*)str
//{
//    NSString* content = nil;
//    NSArray* arr = [_emailDic objectForKey:@"results"];
//    for (int i=0; i<[arr count]; i++) {
//        NSDictionary* curDic = [arr objectAtIndex:i];
//        if ([str isEqualToString:[curDic objectForKey:@"id"]]) {
//            content = [curDic objectForKey:@"content"];
//            break;
//        }
//    }
//    return content;
//}

//按照salerID查找对应的salerName
-(NSString*)getSalerNameByKey:(NSString*)salerID
{
    NSString* name = nil;
    NSArray* arr = [_salersDic objectForKey:@"results"];
    for (int i=0; i<[arr count]; i++) {
        NSDictionary* curDic = [arr objectAtIndex:i];
        if ([salerID isEqualToString:[curDic objectForKey:@"salerID"]]) {
            name = [curDic objectForKey:@"name"];
            break;
        }
    }
    return name;
}

//#pragma mark - UIAlertViewDelegate
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//    if (1 == buttonIndex) {
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPUpdateURL]];
//    }
//}

@end
